#!/bin/sh

if [ -z "$reason" ]; then
	  echo "this script must be called from openconnect-compatible environment"
	  exit 1
fi

case "$reason" in
    connect)
        echo "Clearing VPN device $TUNDEV..."
        ip address flush dev opcon
        echo "Forcing VPN interface $TUNDEV up with $INTERNAL_IP4_MTU MTU..."
        ip link set $TUNDEV up mtu "$INTERNAL_IP4_MTU"
        echo "Setting VPN endpoint IP address $INTERNAL_IP4_ADDRESS/$INTERNAL_IP4_NETMASKLEN..."
        ip address add "$INTERNAL_IP4_ADDRESS/$INTERNAL_IP4_NETMASKLEN" peer "$INTERNAL_IP4_ADDRESS" dev "$TUNDEV"
        echo "Setting up VPN-specific routes..."
        if [ -n "$CISCO_SPLIT_INC" ]; then
	    i=0
	    while [ $i -lt "$CISCO_SPLIT_INC" ] ; do
                eval DST="\${CISCO_SPLIT_INC_${i}_ADDR}"
                eval MLEN="\${CISCO_SPLIT_INC_${i}_MASKLEN}"
                ip route add "$DST/$MLEN" mtu "$INTERNAL_IP4_MTU" dev "$TUNDEV"
		i=$((i + 1))
	    done
	fi
        echo "Adding VPN-specific DNS $INTERNAL_IP4_DNS..."
        resolvectl dns "$TUNDEV" $INTERNAL_IP4_DNS
        resolvectl domain "$TUNDEV" $CISCO_DEF_DOMAIN
	;;
    disconnect)
        echo "Clearing VPN device $TUNDEV..."
        ip address flush dev opcon
        echo "Cleaning up DNS..."
	resolvectl revert "$TUNDEV"
	;;
    *)
	echo "Ignoring unknown reason '$reason'."
	;;
esac
